package com.bluezone.dec.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.CodeEnum;
import com.bluezone.dec.common.JsonResult;
import com.bluezone.dec.common.annotation.AuthPermission;
import com.bluezone.dec.system.service.UserService;
import com.bluezone.dec.uac.UACServiceFactory;
import com.c503.sc.utils.response.ResultMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import sc.c503.authclient.service.splitImpl.ApiUserService;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;


@Api(tags = "用户管理")
@RestController
@RequestMapping("/dec/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("验证token测试")
    @GetMapping("/auth-token")
    public JsonResult authToken(HttpServletRequest request) {
        ApiUserService apiUserService = new ApiUserService(request.getHeader("asoco-token"));
        ResultMessage resultMessage = apiUserService.authToken();

        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg(resultMessage.getMsg());
        jsonResult.setCode(resultMessage.getCode());
        jsonResult.setData(resultMessage.getData());

        return jsonResult;
    }

    @ApiOperation("验证权限测试")
    @GetMapping("/auth")
    @AuthPermission(value = "yzt")
    public JsonResult authPermission() {
        JsonResult jsonResult = new JsonResult();
        return jsonResult.ok();
    }

    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/get-user-info")
    public JsonResult getUserInfo() {
        JsonResult jsonResult = new JsonResult();
        return jsonResult.ok(userService.getUserInfo());
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public JsonResult logout(HttpServletRequest request) {
        String token = request.getHeader("asoco-token");
        if (token == null || "".equals(token)) {
            return new JsonResult().sendCode(CodeEnum.USER_NOLOGOUT);
        }
        // 从uac退出登录
        UACServiceFactory.apiLoginService().logout(token, "");
        // 从缓存清除用户信息
        userService.deleteUserInfo();
        return new JsonResult().ok();
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public JsonResult login(String username, String password) {
        JSONObject result = userService.login(username, new String(Base64Utils.decodeFromString(password)));
        if (result != null) {
            return new JsonResult().ok(result);
        }
        return new JsonResult().error();
    }

}
